package com.lzy.service.impl;

import com.lzy.NotFoundException;
import com.lzy.dao.TagRepository;
import com.lzy.po.Tag;
import com.lzy.po.Type;
import com.lzy.service.TagService;
import com.lzy.util.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * @autor shkstart
 * @create 2021-01-06 10:46)
 */

@Service
public class TagServiceImpl implements TagService {


    @Autowired
    private TagRepository tagRepository;

    @Override
    public Tag saveTag(Tag tag) {
        return tagRepository.save(tag);
    }

    @Override
    public List<Tag> listTag() {
        return tagRepository.findAll();
    }

    @Override
    public List<Tag> listTag(String ids) {
        //根据逗号隔开的多个id
        return tagRepository.findAllById(StringUtil.converToList(ids));
    }


    @Override
    public Tag getTag(Long id) {
        return tagRepository.findById(id).get();
    }

    @Override
    public Tag getTagByName(String name) {
        return tagRepository.findByName(name);
    }

    @Override
    public Page<Tag> listTag(Pageable pageable) {
        return tagRepository.findAll(pageable);
    }

    @Override
    public Tag updateTag(Long id, Tag tag) {
        Tag t = tagRepository.findById(id).get();
        if(t == null){
            throw new NotFoundException();
        }
        BeanUtils.copyProperties(tag,t);

        /*
        * 调用save方法可能有两种情况
        若db中这个id对应的字段不存在，则插入
        若db中这个id对应的字段存在，则更新
        * */
        return tagRepository.save(t);
    }

    @Override
    public void deleteTag(Long id) {
        tagRepository.deleteById(id);
    }

    @Override
    public List<Tag> listTag(Integer size) {
        Sort.Order sort = new Sort.Order(Sort.Direction.DESC,"blogs.size"); //根据标签中的博客数排序
        Pageable pageable = PageRequest.of(0,size,Sort.by(sort)); //只显示第一页
        return tagRepository.findTop(pageable);
    }

}
